package com.kaishengit.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kaishengit.dao.MessageDao;
import com.kaishengit.entity.Message;
import com.kaishengit.entity.User;
import com.kaishengit.entity.UserPro;
import com.kaishengit.service.MessageService;
import com.kaishengit.service.New_projectService;
import com.kaishengit.util.Page;
import com.kaishengit.util.TimeUtil;
import com.kaishengit.util.UuidUtil;

public class ProjectServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String method = request.getParameter("m");
		if(method == null || "".equals(method)) {
			String id = request.getParameter("id");
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute("user");
			New_projectService nps = new New_projectService();
			UserPro userpro = nps.findByUseridAndProId(user.getId(),id);
			session.setAttribute("userpro", userpro);
			
			String p = request.getParameter("p");
			int pageNum = 0;
			if(p == null || "".equals(p)) {
				pageNum = 1;
			}else {
				try {
					pageNum = Integer.parseInt(p);
				} catch (NumberFormatException e) {
					pageNum = 1;
				}
			}
			MessageService ms = new MessageService();
			Page<Message> page = ms.findByProId(id,pageNum);
			
			request.setAttribute("page", page);
			
			request.getRequestDispatcher("/WEB-INF/views/project.jsp").forward(request, response);
		}else if("publish".equals(method)) {
			publish(request,response);
		}
	
	}

	private void publish(HttpServletRequest request,
			HttpServletResponse response) {
		String content = request.getParameter("textarea");
		String id = new UuidUtil().getId();
		long createTime = new TimeUtil().getTime();
		HttpSession session = request.getSession();
		UserPro userpro = (UserPro) session.getAttribute("userpro");
		String proId = userpro.getProId();
		String userId = userpro.getUserId();
		Message m = new Message();
		m.setId(id);
		m.setContent(content);
		m.setCreateTime(createTime);
		m.setProId(proId);
		m.setUserId(userId);
		
		MessageService ms = new MessageService();
		ms.save(m);
		try {
			response.sendRedirect("project.jspx?id="+userpro.getProId());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}
